package com.fuyao.cloud.asset.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.fuyao.cloud.common.data.resolver.ParamResolver;
import org.apache.commons.compress.utils.Lists;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author ly
 * @date 2021/11/19 14:44
 */
public class YearUtils {

	/**
	 * 根据系统配置加载年份集合
	 * @return 年份集合
	 */
	private static List<Integer> getYearList(){
		int startYear = ParamResolver.getInt("FUYAO_START_YEAR");
		int year = DateUtil.year(new Date());
		List<Integer> yearList = Lists.newArrayList();
		for (int i = startYear; i <= year; i++) {
			yearList.add(i);
		}
		return yearList;
	}

	/**
	 * 获取月份集合
	 * @return 1~12月份集合。
	 */
	private static List<Integer> getMonthList(){
		List<Integer> monthList = Lists.newArrayList();
		for (int i = 0; i < 12; i++) {
			monthList.add((i+1));
		}
		return monthList;
	}

	/**
	 * 返回对年份和月份构建的树
	 * @return 年份树集合
	 */
	public static List<Tree<Integer>> getYearTreeList(){
		List<TreeNode<Integer>> collect = getYearList().stream()
				.sorted().map(y -> {
					TreeNode<Integer> treeNode = new TreeNode();
					treeNode.setId(y);
					treeNode.setParentId(0);
					treeNode.setName(String.valueOf(y));
					treeNode.setWeight(120);
					Map<String, Object> extra = new HashMap<>(2);
					extra.put("type", "YEAR");
					treeNode.setExtra(extra);
					return treeNode;
				}).collect(Collectors.toList());
		// 添加月份
		AtomicInteger index = new AtomicInteger(1);
		getYearList().forEach(year->{
			getMonthList().forEach(month->{
				TreeNode<Integer> treeNode = new TreeNode();
				int andIncrement = index.getAndIncrement();
				treeNode.setId(andIncrement);
				treeNode.setParentId(year);
				treeNode.setName(String.valueOf(month));
				treeNode.setWeight(120);
				Map<String, Object> extra = new HashMap<>(2);
				extra.put("type", "MONTH");
				treeNode.setExtra(extra);
				collect.add(treeNode);
			});
		});

		TreeNode<Integer> parentCode = new TreeNode();
		parentCode.setId(0);
		parentCode.setName("全部");
		parentCode.setParentId(-1);
		parentCode.setWeight(120);

		collect.add(parentCode);
		return TreeUtil.build(collect, -1);
	}
}
